package net.xujialiang.XTestRPA.Controller.UserManager;

import net.xujialiang.XTestRPA.Config.SpringSecurityConfig.SecurityUser;
import net.xujialiang.XTestRPA.Entity.XRPAUser;
import net.xujialiang.XTestRPA.Model.ResultData;
import net.xujialiang.XTestRPA.Service.XRPAUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

import static net.xujialiang.XTestRPA.Enum.ReturnCode.RC999;

@RestController
@RequestMapping("/api/user")
public class User {
    @Autowired
    XRPAUserService userService;

    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResultData<Map<String, Object>> getuserInfo(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        XRPAUser user = sUser.getCurrentUserInfo();
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("username", user.getUsername());
        ret.put("ttc", user.getTtc());
        ret.put("nickName", user.getNickName());
        return ResultData.success(ret);
    }

    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    public ResultData<Map<String, Object>> updatePwd(@RequestBody Map<String, Object> reqBody, HttpServletRequest request, Authentication auth) {
        String pwd = (String) reqBody.get("password");
        String oldPwd = (String) reqBody.get("oldPassword");
        SecurityUser sUser = (SecurityUser) auth.getPrincipal();
        String ttc = sUser.getTTC();
        String username=sUser.getUsername();
        try {
            userService.updatePwd(username, ttc, pwd, oldPwd);
            return ResultData.success();
        } catch (Exception e) {
            return ResultData.fail(RC999.getCode(), e.getMessage());
        }
    }
}
